package com.jiliason.segmentation.utils;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class StrUtil {

    public static List<String> splittingStr(String str, String regex) {
        if (StringUtils.isBlank(str)) return Lists.newArrayList();

        Matcher matcher = Pattern.compile(regex).matcher(str);

        String replaceStr = str;
        List<String> splits = Lists.newArrayList();

        while (matcher.find()) {
            String group = matcher.group();
            replaceStr = replaceStr.replaceFirst(group, "|&|");
            splits.add(group);
        }

        for (String s : splits) {
            replaceStr = replaceStr.replaceFirst("&", s);
        }

        return Arrays.stream(replaceStr.split("\\|")).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
    }

    public static String combineRegex(String... regexes) {
        StringJoiner regexJoiner = new StringJoiner("|");
        for (String regex : regexes) {
            regexJoiner.add("(" + regex + ")");
        }
        return regexJoiner.toString();
    }
}
